{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pandas rank() - 数据排名详解\n",
    "\n",
    "本教程详细介绍如何使用 `rank()` 方法计算数据的排名。\n",
    "\n",
    "## 目录\n",
    "1. rank() 基础用法\n",
    "2. 排名方法详解\n",
    "3. 处理重复值\n",
    "4. 多列排名\n",
    "5. 分组排名\n",
    "6. 排名的实际应用\n",
    "7. 与其他排序方法的对比"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. rank() 基础用法\n",
    "\n",
    "### 方法说明\n",
    "\n",
    "`rank()` 方法用于计算数据的排名，返回每个元素在排序中的位置。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df.rank(axis=0, method='average', numeric_only=None, \n",
    "        na_option='keep', ascending=True, pct=False)\n",
    "```\n",
    "\n",
    "**主要参数:**\n",
    "- `axis`: 0(按列排名) 或 1(按行排名)，默认 0\n",
    "- `method`: 排名方法，'average', 'min', 'max', 'first', 'dense'\n",
    "- `ascending`: True(升序排名) 或 False(降序排名)，默认 True\n",
    "- `na_option`: 缺失值处理，'keep', 'top', 'bottom'\n",
    "- `pct`: 是否返回百分位排名，默认 False\n",
    "\n",
    "**特点:**\n",
    "- ✅ 返回排名而不是排序后的数据\n",
    "- ✅ 保持原始数据结构和索引\n",
    "- ✅ 支持多种排名方法\n",
    "- ✅ 灵活处理重复值和缺失值\n",
    "\n",
    "**适用场景:** 需要计算排名、百分位、相对位置时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建示例数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始成绩数据:\n",
      "   姓名  数学  英语  语文\n",
      "0  张三  85  90  88\n",
      "1  李四  92  85  90\n",
      "2  王五  78  95  85\n",
      "3  赵六  96  82  94\n",
      "4  孙七  88  91  87\n"
     ]
    }
   ],
   "source": [
    "# 创建学生成绩数据\n",
    "df = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '孙七'],\n",
    "    '数学': [85, 92, 78, 96, 88],\n",
    "    '英语': [90, 85, 95, 82, 91],\n",
    "    '语文': [88, 90, 85, 94, 87]\n",
    "})\n",
    "\n",
    "print(\"原始成绩数据:\")\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 基础排名\n",
    "\n",
    "计算数学成绩的排名。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数学成绩排名（升序）:\n",
      "   姓名  数学  数学排名_升序\n",
      "0  张三  85      2.0\n",
      "1  李四  92      4.0\n",
      "2  王五  78      1.0\n",
      "3  赵六  96      5.0\n",
      "4  孙七  88      3.0\n",
      "\n",
      "数学成绩排名（降序）:\n",
      "   姓名  数学  数学排名_降序\n",
      "0  张三  85      4.0\n",
      "1  李四  92      2.0\n",
      "2  王五  78      5.0\n",
      "3  赵六  96      1.0\n",
      "4  孙七  88      3.0\n"
     ]
    }
   ],
   "source": [
    "# 计算数学成绩排名（升序，分数越低排名越前）\n",
    "df['数学排名_升序'] = df['数学'].rank()\n",
    "print(\"数学成绩排名（升序）:\")\n",
    "print(df[['姓名', '数学', '数学排名_升序']])\n",
    "\n",
    "# 计算数学成绩排名（降序，分数越高排名越前）\n",
    "df['数学排名_降序'] = df['数学'].rank(ascending=False)\n",
    "print(\"\\n数学成绩排名（降序）:\")\n",
    "print(df[['姓名', '数学', '数学排名_降序']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 百分位排名\n",
    "\n",
    "使用 `pct=True` 获取百分位排名。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数学成绩百分位排名:\n",
      "   姓名  数学  数学百分位\n",
      "0  张三  85    0.8\n",
      "1  李四  92    0.4\n",
      "2  王五  78    1.0\n",
      "3  赵六  96    0.2\n",
      "4  孙七  88    0.6\n",
      "\n",
      "百分位说明：1.0表示最高，0.2表示最低\n"
     ]
    }
   ],
   "source": [
    "df['数学百分位'] = df['数学'].rank(pct=True, ascending=False)\n",
    "print(\"数学成绩百分位排名:\")\n",
    "print(df[['姓名', '数学', '数学百分位']])\n",
    "print(\"\\n百分位说明：1.0表示最高，0.2表示最低\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 排名方法详解\n",
    "\n",
    "### 方法说明\n",
    "\n",
    "`method` 参数控制如何处理相同值的排名。\n",
    "\n",
    "**排名方法:**\n",
    "- `'average'`: 相同值取平均排名（默认）\n",
    "- `'min'`: 相同值取最小排名\n",
    "- `'max'`: 相同值取最大排名\n",
    "- `'first'`: 相同值按出现顺序排名\n",
    "- `'dense'`: 密集排名，无间隔\n",
    "\n",
    "**适用场景:** 根据业务需求选择合适的排名方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建包含重复值的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建包含重复分数的数据\n",
    "df_dup = pd.DataFrame({\n",
    "    '学生': ['A', 'B', 'C', 'D', 'E', 'F'],\n",
    "    '分数': [95, 90, 95, 88, 90, 92]\n",
    "})\n",
    "\n",
    "print(\"包含重复分数的数据:\")\n",
    "print(df_dup)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 不同排名方法对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 应用不同的排名方法\n",
    "methods = ['average', 'min', 'max', 'first', 'dense']\n",
    "\n",
    "for method in methods:\n",
    "    df_dup[f'排名_{method}'] = df_dup['分数'].rank(method=method, ascending=False)\n",
    "\n",
    "print(\"不同排名方法对比:\")\n",
    "print(df_dup)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 排名方法详细说明"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"排名方法说明（以降序为例）:\")\n",
    "print(\"\\n分数: [95, 90, 95, 88, 90, 92]\")\n",
    "print(\"\\n各方法结果:\")\n",
    "print(\"average: 相同值取平均排名\")\n",
    "print(\"  95分: (1+3)/2 = 2.0\")\n",
    "print(\"  90分: (4+5)/2 = 4.5\")\n",
    "print()\n",
    "print(\"min: 相同值取最小排名\") \n",
    "print(\"  95分: 1, 90分: 4\")\n",
    "print()\n",
    "print(\"max: 相同值取最大排名\")\n",
    "print(\"  95分: 3, 90分: 5\") \n",
    "print()\n",
    "print(\"first: 按出现顺序排名\")\n",
    "print(\"  第一个95分: 1, 第二个95分: 2\")\n",
    "print()\n",
    "print(\"dense: 密集排名，无间隔\")\n",
    "print(\"  95分: 1, 92分: 2, 90分: 3, 88分: 4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 处理重复值\n",
    "\n",
    "深入理解不同排名方法在处理重复值时的行为。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 体育比赛排名场景"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 模拟体育比赛成绩\n",
    "race_results = pd.DataFrame({\n",
    "    '选手': ['选手A', '选手B', '选手C', '选手D', '选手E'],\n",
    "    '时间': [10.2, 10.1, 10.2, 10.3, 10.1]  # 秒\n",
    "})\n",
    "\n",
    "print(\"比赛成绩（时间越短越好）:\")\n",
    "print(race_results)\n",
    "\n",
    "# 不同排名方法\n",
    "race_results['排名_average'] = race_results['时间'].rank(method='average')\n",
    "race_results['排名_min'] = race_results['时间'].rank(method='min') \n",
    "race_results['排名_dense'] = race_results['时间'].rank(method='dense')\n",
    "\n",
    "print(\"\\n不同排名方法:\")\n",
    "print(race_results)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 考试成绩排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 考试成绩排名\n",
    "exam_scores = pd.DataFrame({\n",
    "    '学生': ['张三', '李四', '王五', '赵六', '孙七', '周八'],\n",
    "    '总分': [285, 290, 285, 275, 290, 280]\n",
    "})\n",
    "\n",
    "print(\"考试总分:\")\n",
    "print(exam_scores)\n",
    "\n",
    "# 学术排名通常使用 min 方法（并列第一名）\n",
    "exam_scores['学术排名'] = exam_scores['总分'].rank(method='min', ascending=False)\n",
    "\n",
    "# 竞赛排名可能使用 dense 方法\n",
    "exam_scores['竞赛排名'] = exam_scores['总分'].rank(method='dense', ascending=False)\n",
    "\n",
    "print(\"\\n不同场景的排名:\")\n",
    "print(exam_scores[['学生', '总分', '学术排名', '竞赛排名']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 多列排名\n",
    "\n",
    "对多个列同时计算排名。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法说明\n",
    "\n",
    "可以对 DataFrame 的多列同时计算排名。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df[['列1', '列2']].rank()\n",
    "```\n",
    "\n",
    "**特点:**\n",
    "- 每列独立计算排名\n",
    "- 保持数据结构\n",
    "- 可以应用不同参数\n",
    "\n",
    "**适用场景:** 需要对多个指标同时排名时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 多科目成绩排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 原始成绩数据\n",
    "df_multi = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '孙七'],\n",
    "    '数学': [85, 92, 78, 96, 88],\n",
    "    '英语': [90, 85, 95, 82, 91],\n",
    "    '语文': [88, 90, 85, 94, 87]\n",
    "})\n",
    "\n",
    "print(\"原始成绩:\")\n",
    "print(df_multi)\n",
    "\n",
    "# 对所有科目计算排名\n",
    "rank_cols = ['数学', '英语', '语文']\n",
    "for col in rank_cols:\n",
    "    df_multi[f'{col}排名'] = df_multi[col].rank(ascending=False)\n",
    "\n",
    "print(\"\\n各科排名:\")\n",
    "print(df_multi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 综合排名计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算总分和综合排名\n",
    "df_multi['总分'] = df_multi[['数学', '英语', '语文']].sum(axis=1)\n",
    "df_multi['总分排名'] = df_multi['总分'].rank(ascending=False)\n",
    "\n",
    "# 计算平均排名\n",
    "df_multi['平均排名'] = df_multi[['数学排名', '英语排名', '语文排名']].mean(axis=1)\n",
    "\n",
    "print(\"综合排名:\")\n",
    "print(df_multi[['姓名', '总分', '总分排名', '平均排名']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 分组排名\n",
    "\n",
    "在分组内计算排名。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法说明\n",
    "\n",
    "使用 `groupby()` 结合 `rank()` 可以在组内计算排名。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df.groupby('分组列')['数值列'].rank()\n",
    "```\n",
    "\n",
    "**特点:**\n",
    "- 每个组内独立排名\n",
    "- 排名从1开始重新计算\n",
    "- 适合分类比较\n",
    "\n",
    "**适用场景:** 需要在不同类别内比较排名时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 按班级分组排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建多班级学生数据\n",
    "df_class = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '孙七', '周八'],\n",
    "    '班级': ['A班', 'A班', 'B班', 'B班', 'A班', 'B班'],\n",
    "    '成绩': [85, 92, 78, 96, 88, 90]\n",
    "})\n",
    "\n",
    "print(\"多班级学生成绩:\")\n",
    "print(df_class)\n",
    "\n",
    "# 班级内排名\n",
    "df_class['班级内排名'] = df_class.groupby('班级')['成绩'].rank(ascending=False)\n",
    "\n",
    "# 全校排名\n",
    "df_class['全校排名'] = df_class['成绩'].rank(ascending=False)\n",
    "\n",
    "print(\"\\n班级内排名 vs 全校排名:\")\n",
    "print(df_class)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 按部门分组的员工排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 员工绩效数据\n",
    "employee_data = pd.DataFrame({\n",
    "    '员工': ['张三', '李四', '王五', '赵六', '孙七', '周八'],\n",
    "    '部门': ['销售', '技术', '销售', '技术', '销售', '技术'],\n",
    "    '绩效分': [85, 92, 78, 96, 88, 90]\n",
    "})\n",
    "\n",
    "print(\"员工绩效数据:\")\n",
    "print(employee_data)\n",
    "\n",
    "# 部门内排名\n",
    "employee_data['部门排名'] = employee_data.groupby('部门')['绩效分'].rank(\n",
    "    method='min', ascending=False)\n",
    "\n",
    "# 部门内百分位\n",
    "employee_data['部门百分位'] = employee_data.groupby('部门')['绩效分'].rank(\n",
    "    pct=True, ascending=False)\n",
    "\n",
    "print(\"\\n部门内排名:\")\n",
    "print(employee_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 时间序列分组排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建月度销售数据\n",
    "monthly_sales = pd.DataFrame({\n",
    "    '月份': ['2023-01', '2023-01', '2023-02', '2023-02', '2023-03', '2023-03'],\n",
    "    '销售员': ['张三', '李四', '张三', '李四', '张三', '李四'],\n",
    "    '销售额': [10000, 12000, 11000, 9000, 13000, 14000]\n",
    "})\n",
    "\n",
    "print(\"月度销售数据:\")\n",
    "print(monthly_sales)\n",
    "\n",
    "# 每月内的排名\n",
    "monthly_sales['月度排名'] = monthly_sales.groupby('月份')['销售额'].rank(\n",
    "    ascending=False)\n",
    "\n",
    "print(\"\\n每月销售排名:\")\n",
    "print(monthly_sales)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. 排名的实际应用\n",
    "\n",
    "rank() 在实际数据分析中的应用场景。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 应用1: 股票表现排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 股票表现数据\n",
    "stock_performance = pd.DataFrame({\n",
    "    '股票代码': ['000001', '000002', '600000', '600036', '000858'],\n",
    "    '股票名称': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液'],\n",
    "    '涨跌幅': [2.5, -1.8, 3.2, 1.9, -2.1],\n",
    "    '成交量': [1200000, 800000, 1500000, 900000, 600000],\n",
    "    '市值': [3200, 2800, 2100, 4500, 3800]\n",
    "})\n",
    "\n",
    "print(\"股票表现数据:\")\n",
    "print(stock_performance)\n",
    "\n",
    "# 各指标排名\n",
    "stock_performance['涨跌幅排名'] = stock_performance['涨跌幅'].rank(ascending=False)\n",
    "stock_performance['成交量排名'] = stock_performance['成交量'].rank(ascending=False)\n",
    "stock_performance['市值排名'] = stock_performance['市值'].rank(ascending=False)\n",
    "\n",
    "print(\"\\n股票各指标排名:\")\n",
    "print(stock_performance[['股票名称', '涨跌幅排名', '成交量排名', '市值排名']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 应用2: 产品销售排名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 产品销售数据\n",
    "product_sales = pd.DataFrame({\n",
    "    '产品': ['产品A', '产品B', '产品C', '产品D', '产品E'],\n",
    "    '销售额': [150000, 120000, 180000, 90000, 160000],\n",
    "    '利润率': [0.15, 0.25, 0.12, 0.30, 0.18],\n",
    "    '客户满意度': [4.2, 4.5, 4.1, 4.8, 4.3]\n",
    "})\n",
    "\n",
    "print(\"产品销售数据:\")\n",
    "print(product_sales)\n",
    "\n",
    "# 计算综合排名\n",
    "product_sales['销售额排名'] = product_sales['销售额'].rank(ascending=False)\n",
    "product_sales['利润率排名'] = product_sales['利润率'].rank(ascending=False)\n",
    "product_sales['满意度排名'] = product_sales['客户满意度'].rank(ascending=False)\n",
    "\n",
    "# 综合得分（可以加权）\n",
    "product_sales['综合得分'] = (\n",
    "    product_sales['销售额排名'] * 0.4 +\n",
    "    product_sales['利润率排名'] * 0.3 +\n",
    "    product_sales['满意度排名'] * 0.3\n",
    ")\n",
    "product_sales['综合排名'] = product_sales['综合得分'].rank()\n",
    "\n",
    "print(\"\\n产品综合排名:\")\n",
    "print(product_sales[['产品', '综合得分', '综合排名']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 应用3: 学生成绩分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 学生成绩分析\n",
    "student_analysis = pd.DataFrame({\n",
    "    '学生': ['学生A', '学生B', '学生C', '学生D', '学生E'],\n",
    "    '期中成绩': [85, 92, 78, 96, 88],\n",
    "    '期末成绩': [88, 89, 82, 94, 91],\n",
    "    '作业分': [90, 85, 95, 92, 87]\n",
    "})\n",
    "\n",
    "print(\"学生成绩数据:\")\n",
    "print(student_analysis)\n",
    "\n",
    "# 计算总成绩和排名\n",
    "student_analysis['总成绩'] = (\n",
    "    student_analysis['期中成绩'] * 0.3 +\n",
    "    student_analysis['期末成绩'] * 0.5 +\n",
    "    student_analysis['作业分'] * 0.2\n",
    ")\n",
    "\n",
    "student_analysis['排名'] = student_analysis['总成绩'].rank(ascending=False)\n",
    "student_analysis['百分位'] = student_analysis['总成绩'].rank(pct=True, ascending=False)\n",
    "\n",
    "# 等级划分\n",
    "def get_grade(percentile):\n",
    "    if percentile >= 0.8:\n",
    "        return 'A'\n",
    "    elif percentile >= 0.6:\n",
    "        return 'B'\n",
    "    elif percentile >= 0.4:\n",
    "        return 'C'\n",
    "    else:\n",
    "        return 'D'\n",
    "\n",
    "student_analysis['等级'] = student_analysis['百分位'].apply(get_grade)\n",
    "\n",
    "print(\"\\n学生成绩分析:\")\n",
    "print(student_analysis[['学生', '总成绩', '排名', '百分位', '等级']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. 与其他排序方法的对比\n",
    "\n",
    "rank() 与其他排序方法的区别和联系。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建示例数据\n",
    "comparison_data = pd.DataFrame({\n",
    "    '数值': [85, 92, 78, 96, 88]\n",
    "}, index=['A', 'B', 'C', 'D', 'E'])\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(comparison_data)\n",
    "\n",
    "# 1. rank() - 返回排名\n",
    "ranks = comparison_data['数值'].rank(ascending=False)\n",
    "print(\"\\n1. rank() - 排名:\")\n",
    "print(ranks)\n",
    "\n",
    "# 2. sort_values() - 返回排序后的数据\n",
    "sorted_data = comparison_data.sort_values('数值', ascending=False)\n",
    "print(\"\\n2. sort_values() - 排序后的数据:\")\n",
    "print(sorted_data)\n",
    "\n",
    "# 3. nlargest() - 返回最大的N个\n",
    "top3 = comparison_data.nlargest(3, '数值')\n",
    "print(\"\\n3. nlargest(3) - 前3名:\")\n",
    "print(top3)\n",
    "\n",
    "# 4. argsort() - 返回排序索引\n",
    "sort_indices = comparison_data['数值'].argsort()[::-1]\n",
    "print(\"\\n4. argsort() - 排序索引:\")\n",
    "print(sort_indices)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用场景对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"不同方法的使用场景:\")\n",
    "print()\n",
    "print(\"📊 rank():\")\n",
    "print(\"  ✅ 计算排名、百分位\")\n",
    "print(\"  ✅ 保持原始索引和结构\")\n",
    "print(\"  ✅ 分组内排名\")\n",
    "print(\"  ✅ 排名分析、绩效评估\")\n",
    "print()\n",
    "print(\"🔄 sort_values():\")\n",
    "print(\"  ✅ 重新排列数据顺序\")\n",
    "print(\"  ✅ 数据展示和分析\")\n",
    "print(\"  ✅ 复杂的多列排序\")\n",
    "print()\n",
    "print(\"⭐ nlargest/nsmallest():\")\n",
    "print(\"  ✅ 快速获取极值\")\n",
    "print(\"  ✅ Top-N 分析\")\n",
    "print(\"  ✅ 性能优化\")\n",
    "print()\n",
    "print(\"🎯 选择建议:\")\n",
    "print(\"  • 需要排名数字 → rank()\")\n",
    "print(\"  • 需要重排数据 → sort_values()\")\n",
    "print(\"  • 只要前几名 → nlargest()\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 综合示例: 员工绩效评估系统"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 综合示例：员工绩效评估\n",
    "performance_data = pd.DataFrame({\n",
    "    '员工ID': ['E001', 'E002', 'E003', 'E004', 'E005', 'E006'],\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '孙七', '周八'],\n",
    "    '部门': ['销售', '技术', '销售', '技术', '销售', '技术'],\n",
    "    '销售业绩': [120, 0, 95, 0, 110, 0],  # 技术部门无销售业绩\n",
    "    '技术评分': [0, 95, 0, 88, 0, 92],    # 销售部门无技术评分\n",
    "    '团队协作': [85, 90, 78, 92, 88, 87],\n",
    "    '工作态度': [88, 85, 90, 89, 86, 91]\n",
    "})\n",
    "\n",
    "print(\"员工绩效原始数据:\")\n",
    "print(performance_data)\n",
    "\n",
    "# 按部门分别计算排名\n",
    "sales_mask = performance_data['部门'] == '销售'\n",
    "tech_mask = performance_data['部门'] == '技术'\n",
    "\n",
    "# 销售部门排名（销售业绩 + 软技能）\n",
    "sales_data = performance_data[sales_mask].copy()\n",
    "sales_data['综合得分'] = (\n",
    "    sales_data['销售业绩'] * 0.6 +\n",
    "    sales_data['团队协作'] * 0.2 +\n",
    "    sales_data['工作态度'] * 0.2\n",
    ")\n",
    "sales_data['部门排名'] = sales_data['综合得分'].rank(ascending=False)\n",
    "\n",
    "# 技术部门排名（技术评分 + 软技能）\n",
    "tech_data = performance_data[tech_mask].copy()\n",
    "tech_data['综合得分'] = (\n",
    "    tech_data['技术评分'] * 0.6 +\n",
    "    tech_data['团队协作'] * 0.2 +\n",
    "    tech_data['工作态度'] * 0.2\n",
    ")\n",
    "tech_data['部门排名'] = tech_data['综合得分'].rank(ascending=False)\n",
    "\n",
    "# 合并结果\n",
    "final_result = pd.concat([sales_data, tech_data])\n",
    "final_result = final_result.sort_values('员工ID')\n",
    "\n",
    "print(\"\\n员工绩效排名结果:\")\n",
    "print(final_result[['姓名', '部门', '综合得分', '部门排名']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "### rank() 方法总结\n",
    "\n",
    "| 参数 | 默认值 | 说明 | 常用值 |\n",
    "|------|--------|------|--------|\n",
    "| `method` | 'average' | 排名方法 | 'average', 'min', 'max', 'first', 'dense' |\n",
    "| `ascending` | True | 排序方向 | True(升序), False(降序) |\n",
    "| `axis` | 0 | 排名轴向 | 0(按列), 1(按行) |\n",
    "| `na_option` | 'keep' | 缺失值处理 | 'keep', 'top', 'bottom' |\n",
    "| `pct` | False | 百分位排名 | True, False |\n",
    "\n",
    "### 排名方法对比\n",
    "\n",
    "| 方法 | 重复值处理 | 适用场景 |\n",
    "|------|-----------|----------|\n",
    "| `average` | 取平均排名 | 一般统计分析 |\n",
    "| `min` | 取最小排名 | 学术排名、体育比赛 |\n",
    "| `max` | 取最大排名 | 保守排名 |\n",
    "| `first` | 按出现顺序 | 时间序列、先到先得 |\n",
    "| `dense` | 密集排名 | 等级划分 |\n",
    "\n",
    "### 关键要点\n",
    "\n",
    "1. **返回排名**: rank() 返回排名数字，不改变数据顺序\n",
    "2. **保持结构**: 保持原始 DataFrame 的索引和结构\n",
    "3. **处理重复**: 多种方法处理相同值的排名\n",
    "4. **分组排名**: 结合 groupby() 实现组内排名\n",
    "5. **百分位**: pct=True 返回百分位排名\n",
    "6. **缺失值**: 灵活的缺失值处理选项\n",
    "\n",
    "### 最佳实践\n",
    "\n",
    "```python\n",
    "# ✅ 推荐用法\n",
    "df['排名'] = df['分数'].rank(ascending=False)  # 基础排名\n",
    "df['百分位'] = df['分数'].rank(pct=True)  # 百分位排名\n",
    "df.groupby('类别')['数值'].rank()  # 分组排名\n",
    "\n",
    "# 🎯 场景选择\n",
    "# 学术排名 → method='min'\n",
    "# 体育比赛 → method='min' \n",
    "# 一般分析 → method='average'\n",
    "# 等级划分 → method='dense'\n",
    "```\n",
    "\n",
    "### rank() vs 其他方法\n",
    "\n",
    "| 需求 | 推荐方法 | 原因 |\n",
    "|------|---------|------|\n",
    "| 计算排名 | rank() | 专门用于排名计算 |\n",
    "| 数据排序 | sort_values() | 重新排列数据 |\n",
    "| 前N名数据 | nlargest() | 性能更好 |\n",
    "| 分组排名 | groupby().rank() | 组内独立排名 |"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml311",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
